<template>
  <div class="app-container">
    <div class="filter-container">
      <org-unit-select v-model="filters.orgUnitId" placeholder="请选择店铺" :org-unit-type="1"/>
      <shop-movie-select v-model="filters.shopMovieId" />
      <el-date-picker
        v-model="selectedDate"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        value-format="yyyy-MM-dd"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions">
      </el-date-picker>
      <el-radio-group v-model="filters.status" style="margin: 0 3px;" >
        <el-radio-button :label="1" @click.native.prevent="statusFilter(1)">拼车中</el-radio-button>
        <el-radio-button :label="2" @click.native.prevent="statusFilter(2)">已发车</el-radio-button>
      </el-radio-group>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button v-if="canAddCarpool" v-waves class="filter-item" type="primary" icon="el-icon-add" @click="handleAdd">添加</el-button>
      <div style="margin-left: 3.125rem;">
        <el-checkbox v-for="col in dynamicColumn.carpools" v-model="col.show" class="filter-item" style="margin-left:10px;" @change="tableKey=tableKey+1">
          {{ col.name }}
        </el-checkbox>
      </div>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      border
      fit
      :height="tableHeight"
      :data="list"
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="selsChange"
    >
      <el-table-column type="index" width="60" />
      <el-table-column prop="orgUnitName" label="店铺" min-width="160" />
      <el-table-column prop="title" label="标题" min-width="160" />
      <el-table-column v-if="checkColumn('movieName')" prop="movieName" label="剧本名称" min-width="220" />
      <el-table-column v-if="checkColumn('tag')" prop="tag" label="剧本标签" min-width="120" :formatter="formatTag" />
      <el-table-column v-if="checkColumn('status')" prop="status" label="状态" width="70" :formatter="formatStatus" />
      <el-table-column prop="startTime" label="约车时间" min-width="155" />
      <el-table-column v-if="checkColumn('playerCount')" prop="playerCount" label="玩家数量" min-width="80" />
      <el-table-column v-if="checkColumn('playerCount')" prop="joinedPlayerCount" label="加入玩家数量" min-width="110" />
      <el-table-column v-if="checkColumn('beginTime')" prop="beginTime" label="发车时间" min-width="155" />
      <el-table-column v-if="checkColumn('beginnerId')" prop="beginnerId" label="发车人" min-width="120" :formatter="formatBeginner" />
      <el-table-column v-if="checkColumn('terminateTime')" prop="terminateTime" label="结束时间" min-width="155" />
      <el-table-column v-if="checkColumn('terminatorId')" prop="terminatorId" label="结束人" min-width="120" :formatter="formatTerminator" />
      <el-table-column v-if="checkColumn('confirmTime')" prop="confirmTime" label="确认时间" min-width="155" />
      <el-table-column v-if="checkColumn('confirmorId')" prop="confirmorId" label="确认人" min-width="120" :formatter="formatConfirmor" />
      <el-table-column v-if="checkColumn('operation')" label="操作" width="220" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.index, scope.row)">编辑</el-button>
          <el-button size="small" @click="handleConfirm(scope.index, scope.row)">确认</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="filters.page" :limit.sync="filters.limit" @pagination="loadPageList" />

    <!--新增界面-->
    <el-dialog title="车次信息" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" :label-width="formLabelWidth" :rules="addFormRules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="addForm.title"></el-input>
        </el-form-item>
        <el-form-item label="剧本" prop="shopMovieId">
          <shop-movie-select v-model="addForm.shopMovieId" />
        </el-form-item>
        <el-form-item label="剧本标签" prop="tag">
          <movie-tag-select v-model="addForm.tag" />
        </el-form-item>
        <el-form-item label="玩家数量" prop="playerCount">
          <el-input-number v-model="addForm.playerCount" :min="1" />
        </el-form-item>
        <el-form-item label="发车时间" prop="startTime">
          <el-date-picker
            v-model="addForm.startTime"
            type="datetime"
            placeholder="请选择发车时间"
            default-time="12:00:00"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="addLoading" @click="addSubmit">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCarpool, modifyCarpool, saveCarpool, deleteCarpool, confirmCarpool } from '@/api/carpools'
import OrgUnitSelect from '../components/org-unit-select'
import ShopMovieSelect from '../components/shop-movie-select'
import waves from '@/directive/waves' // waves directive
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination'
import MovieTagSelect from '@/views/components/movie-tag-select'

export default {
  name: 'Carpools',
  components: { MovieTagSelect, Pagination, OrgUnitSelect, ShopMovieSelect },
  directives: { waves },
  data() {
    return {
      tableHeight: 260,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      sels: [], // 列表选中列
      filters: {
        page: 1,
        limit: 20,
        shopMovieId: null,
        orgUnitId: null,
        status: null
      },
      selectedDate: '',
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近30天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近90天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      orderBy: {
        orderColumn: '',
        order: ''
      },

      // 新增界面是否显示
      addFormVisible: false,
      addLoading: false,
      addFormRules: {
        shopMovieId: [{ required: false, message: '请选择剧本', trigger: 'blur' }],
        startTime: [{ required: false, message: '请选择发车时间', trigger: 'blur' }]
      },
      // 新增界面数据
      recordId: 0,
      addForm: {
        title: null,
        shopMovieId: null,
        startTime: null,
        tag: null,
        playerCount: null,
        version: null
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'formLabelWidth', 'dynamicColumn']),
    canAddCarpool() {
      const roles = this.userInfo.roles || []
      if (roles.indexOf('ShopManager') !== -1 || roles.indexOf('DM') !== -1) {
        return true
      }
      if (roles.indexOf('Manager') !== -1) {
        if (this.userInfo.orgUnitType === 1) {
          // 店铺
          return true
        }
      }
      return false
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 220
    this.loadPageList()
  },
  methods: {
    checkColumn(col) {
      if (this.dynamicColumn.carpools.hasOwnProperty(col)) {
        return this.dynamicColumn.carpools[col].show
      }
      return true
    },
    formatTag(row) {
      if (row.tag && Array.isArray(row.tag)) {
        return row.tag.join(' ')
      }
    },
    formatStatus(row) {
      if (row.status === 1) {
        return '拼车中'
      } else if (row.status === 2) {
        return '已发车'
      }
      return row.status
    },
    formatBeginner(row) {
      return row.beginnerNickname || row.beginnerPhoneNumber || ''
    },
    formatTerminator(row) {
      return row.terminatorNickname || row.terminatorPhoneNumber || ''
    },
    formatConfirmor(row) {
      return row.confirmorNickname || row.confirmorPhoneNumber || ''
    },
    loadPageList() {
      this.listLoading = true
      const param = { ...this.filters, ...this.orderBy }
      if (this.selectedDate && this.selectedDate.length >= 2) {
        param.start = this.selectedDate[0]
        param.end = this.selectedDate[1]
      }
      listCarpool(param).then(({ success, message, data }) => {
        this.listLoading = false
        if (success) {
          const { records, total } = data || {}
          this.list = records
          this.total = total
        } else {
          this.$message({
            message: message || '查询列表失败',
            type: 'error'
          })
        }
      }, () => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.filters.page = 1
      this.loadPageList()
    },
    statusFilter(status) {
      if (status === this.filters.status) {
        this.filters.status = null
      } else {
        this.filters.status = status
      }
      this.handleFilter()
    },
    sortChange({ prop, order }) {
      this.orderBy.orderColumn = prop
      this.orderBy.order = order
      this.handleFilter()
    },
    selsChange(sels) {
      this.sels = sels
    },
    handleAdd() {
      this.addFormVisible = true
      this.recordId = 0
      this.addForm = {
        title: null,
        shopMovieId: null,
        tag: null,
        startTime: null,
        playerCount: null,
        version: null
      }
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    handleEdit(index, row) {
      this.addFormVisible = true
      this.recordId = row.id
      this.addForm.title = row.title
      this.addForm.shopMovieId = row.shopMovieId
      this.addForm.tag = row.tag
      this.addForm.startTime = row.startTime
      this.addForm.playerCount = row.playerCount
      this.addForm.version = row.version
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    // 新增
    addSubmit: function() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true
            if (this.recordId) {
              this.doEdit()
            } else {
              this.doSave()
            }
          })
        }
      })
    },
    doEdit() {
      modifyCarpool(this.recordId, this.addForm).then(({ success, message }) => {
        this.addLoading = false
        if (success) {
          this.$message({
            message: message || '提交成功',
            type: 'success'
          })
          this.$refs['addForm'].resetFields()
          this.addFormVisible = false
          this.loadPageList()
        } else {
          this.$message({
            message: message || '添加失败',
            type: 'error'
          })
        }
      }, () => {
        this.addLoading = false
      })
    },
    doSave() {
      saveCarpool(this.addForm).then(({ success, message }) => {
        this.addLoading = false
        if (success) {
          this.$message({
            message: message || '提交成功',
            type: 'success'
          })
          this.$refs['addForm'].resetFields()
          this.addFormVisible = false
          this.loadPageList()
        } else {
          this.$message({
            message: message || '添加失败',
            type: 'error'
          })
        }
      }, () => {
        this.addLoading = false
      })
    },
    handleConfirm(index, row) {
      this.$confirm('是否要确认此拼车记录?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        confirmCarpool(row.id).then(({ success, message }) => {
          this.listLoading = false
          if (success) {
            this.$message({
              message: message || '确认成功',
              type: 'success'
            })
            this.loadPageList()
          } else {
            this.$message({
              message: message || '确认失败',
              type: 'error'
            })
          }
        }, (res) => {
          this.listLoading = false
        })
      })
    },
    handleDelete(index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        deleteCarpool(row.id).then(({ success, message }) => {
          this.listLoading = false
          if (success) {
            this.$message({
              message: message || '删除成功',
              type: 'success'
            })
            this.loadPageList()
          } else {
            this.$message({
              message: message || '删除失败',
              type: 'error'
            })
          }
        }, (res) => {
          this.listLoading = false
        })
      }).catch(() => {

      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
